package com.cskaoyan.service.wx;

import com.cskaoyan.bean.cart.*;
import com.cskaoyan.bean.goods.MarketGoods;
import com.cskaoyan.bean.goods.MarketGoodsProduct;
import com.cskaoyan.bean.goods.MarketGoodsProductExample;
import com.cskaoyan.bean.promotion.coupon.Coupon;
import com.cskaoyan.bean.promotion.coupon.CouponExample;
import com.cskaoyan.bean.promotion.coupon.CouponUser;
import com.cskaoyan.bean.promotion.coupon.CouponUserExample;
import com.cskaoyan.bean.user.Address;
import com.cskaoyan.bean.user.AddressExample;
import com.cskaoyan.bean.user.User;
import com.cskaoyan.bean.user.UserExample;
import com.cskaoyan.bean.wx_coupon.WXSelectInnerCoupon;
import com.cskaoyan.bean.wx_coupon.WXShowSelectCouponVO;
import com.cskaoyan.mapper.*;
import com.cskaoyan.mapper.goodsMapper.MarketGoodsMapper;
import com.cskaoyan.mapper.goodsMapper.MarketGoodsProductMapper;
import com.cskaoyan.service.AdministratorsService;
import com.cskaoyan.service.wx.coupon.WXCouponService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    CartMapper cartMapper;

    @Autowired
    MarketGoodsMapper goodsMapper;

    @Autowired
    MarketGoodsProductMapper goodsProductMapper;

    @Autowired
    AddressMapper addressMapper;

    @Autowired
    CouponMapper couponMapper;

    @Autowired
    CouponUserMapper couponUserMapper;

    @Autowired
    MarketGoodsMapper marketGoodsMapper;

    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    WXCouponService wxCouponService;


    @Autowired
    AdministratorsService administratorsService;


    @Override
    public CartIndexVo index() {
        CartExample cartExample = new CartExample();
        //整合shiro
        Integer userId = getUserId();
        cartExample.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        int checkedGoodsCount = 0;
        int checkedGoodsAmount = 0;
        int goodsAmount = 0;
        ArrayList<CartListBean> cartListBeans = new ArrayList<>();
        for (Cart cart : carts) {
            if (cart.getChecked() == true) {
                checkedGoodsCount++;
                checkedGoodsAmount += (cart.getPrice().intValue() * cart.getNumber());
            }
            goodsAmount += cart.getPrice().intValue() * cart.getNumber();
            CartListBean cartListBean = new CartListBean(
                    cart.getId(),
                    cart.getUserId(),
                    cart.getGoodsId(),
                    cart.getGoodsSn(),
                    cart.getGoodsName(),
                    cart.getProductId(),
                    cart.getPrice().intValue(),
                    cart.getNumber(),
                    cart.getChecked(),
                    cart.getPicUrl(),
                    cart.getAddTime(),
                    cart.getUpdateTime(),
                    cart.getDeleted(),
                    cart.getSpecifications());
            cartListBeans.add(cartListBean);
        }
        CartTotalBean cartTotalBean = new CartTotalBean();
        cartTotalBean.setCheckedGoodsAmount(checkedGoodsAmount);
        cartTotalBean.setCheckedGoodsCount(checkedGoodsCount);
        cartTotalBean.setGoodsCount(carts.size());
        cartTotalBean.setGoodsAmount(goodsAmount);
        CartIndexVo cartIndexVo = new CartIndexVo(cartTotalBean, cartListBeans);
        return cartIndexVo;


    }


    @Override
    public CartCheckedVo checked(Map map) {
        Integer userId = getUserId();
        //{"productIds":[45,234,11,292],"isChecked":1}
        List<Integer> productIds = (List<Integer>) map.get("productIds");
        Integer isChecked = (Integer) map.get("isChecked");

        //根据传入进来得数据先对相应用户购物车中商品的checked进行修改
        for (Integer productId : productIds) {
            Cart cart = new Cart();
            if (isChecked == 0) {
                cart.setChecked(false);
            } else {
                cart.setChecked(true);
            }
            CartExample cartExample = new CartExample();
            cartExample.createCriteria().andProductIdEqualTo(productId).andUserIdEqualTo(userId);
            cartMapper.updateByExampleSelective(cart, cartExample);
        }
        //查询所有当前用户checked值，获得checkedGoodsAmount以及checkedGoodsCount
        return getCartCheckedVo();
    }

    private Integer getUserId() {
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipals().getPrimaryPrincipal();
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(userExample);
        return users.get(0).getId();
    }

    //{"productId":103,货品id
    // "goodsId":1086015,商品id
    // "number":3,商品数量
    // "id":22}购物车主键
    //主要更新的是对应用户购物车的对应商品的数量
    @Override
    public void update(Map map) {
        Cart cart = new Cart();
        int number = (int) map.get("number");
        cart.setNumber((short) number);
        Integer id = (Integer) map.get("id");
        cart.setId(id);
        cartMapper.updateByPrimaryKeySelective(cart);
    }

    //{"goodsId":1109004,"number":3,"productId":138}
    @Override
    public Integer add(Map map) {
        //整合shiro
        Integer userId = getUserId();
        Integer goodsId = (Integer) map.get("goodsId");
        int temp = (Integer) map.get("number");
        short number = (short) temp;
        Integer productId = (Integer) map.get("productId");

        //goodsSn、goodsName通过goods表查询
        MarketGoods marketGoods = goodsMapper.selectByPrimaryKey(goodsId);
        String goodsSn = marketGoods.getGoodsSn();
        String goodsName = marketGoods.getName();
        String picUrl = marketGoods.getPicUrl();
        //price、picUrl、specifications通过goodsProduct表查询
        MarketGoodsProduct marketGoodsProduct = goodsProductMapper.selectByPrimaryKey(productId);
        BigDecimal price = marketGoodsProduct.getPrice();
        String[] specifications = marketGoodsProduct.getSpecifications();
        //deleted、checked使用默认值
        Boolean checked = false;
        Boolean deleted = false;

        //判断是否超出所剩余的库存
        MarketGoodsProduct marketGoodsProduct1 = marketGoodsProductMapper.selectByPrimaryKey(productId);
        if (number > marketGoodsProduct1.getNumber()) {
            //库存量不足
            return null;
        }

        //库存量充足，减去当前货品的库存量
        Integer productNumber = marketGoodsProduct1.getNumber();
        productNumber -= number;
        MarketGoodsProduct marketGoodsProduct2 = new MarketGoodsProduct();
        marketGoodsProduct2.setId(productId);
        marketGoodsProduct2.setNumber(productNumber);
        marketGoodsProduct2.setGoodsId(goodsId);
        marketGoodsProductMapper.updateByPrimaryKeySelective(marketGoodsProduct2);

        //先查询cart表格里面是否已有该商品
        CartExample cartExample1 = new CartExample();
        cartExample1.createCriteria().andProductIdEqualTo(productId).andDeletedEqualTo(false);
        List<Cart> carts1 = cartMapper.selectByExample(cartExample1);
        if (carts1.size() == 0) {
            //其余几个字段通过传入的参数进行设定
            Cart cart = new Cart();
            cart.setUserId(userId);
            cart.setGoodsId(goodsId);
            cart.setGoodsSn(goodsSn);
            cart.setGoodsName(goodsName);
            cart.setProductId(productId);
            cart.setPrice(price);
            cart.setNumber((short) number);
            cart.setSpecifications(specifications);
            cart.setChecked(checked);
            cart.setPicUrl(picUrl);
            Date date = new Date();
            cart.setAddTime(date);
            cart.setUpdateTime(date);
            cart.setDeleted(deleted);
            cartMapper.insertSelective(cart);
        }else{
            //cart已经有包含这个货品的记录
            Short number1 = number;
            Short number2 = carts1.get(0).getNumber();
            int productNumber1 = number1 + number2;
            short productNumber2 = (short) productNumber1;
            Cart cart = new Cart();
            cart.setNumber(productNumber2);
            cart.setId(carts1.get(0).getId());
            cartMapper.updateByPrimaryKeySelective(cart);
        }
        int num = 0;
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andUserIdEqualTo(userId);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        for (Cart cart1 : carts) {
            if (cart1.getDeleted() == false) {
                num += cart1.getNumber();
            }
        }
        return num;
    }

    //{"productIds":[297]}
    @Override
    public CartCheckedVo delete(Map map) {
        List<Integer> productIds = (List<Integer>) map.get("productIds");
        //逻辑删除购物车所添加的商品
        //shiro整合
        Integer userId = getUserId();
        for (Integer productId : productIds) {
            CartExample cartExample = new CartExample();
            cartExample.createCriteria().andProductIdEqualTo(productId).andUserIdEqualTo(userId).andDeletedEqualTo(false);
            List<Cart> carts = cartMapper.selectByExample(cartExample);
            Short number = carts.get(0).getNumber();

            //调整库存量
            Integer productId1 = carts.get(0).getProductId();
            MarketGoodsProduct marketGoodsProduct1 = goodsProductMapper.selectByPrimaryKey(productId1);
            int productNumber = marketGoodsProduct1.getNumber() + number;
            MarketGoodsProduct marketGoodsProduct2 = new MarketGoodsProduct();
            marketGoodsProduct2.setNumber(productNumber);
            marketGoodsProduct2.setId(productId);
            marketGoodsProductMapper.updateByPrimaryKeySelective(marketGoodsProduct2);

            //逻辑删除
            Cart cart = new Cart();
            cart.setDeleted(true);
            cartMapper.updateByExampleSelective(cart, cartExample);
        }
        //相应剩余的商品信息
        return getCartCheckedVo();
    }

    @Override
    public int goodscount() {
        //根据当前用户的username查询表当中没有被逻辑删除的商品
        //整合shiro
        Integer userId = getUserId();
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andUserIdEqualTo(userId);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        int number = 0;
        for (Cart cart : carts) {
            if (cart.getDeleted() == false) {
                number += cart.getNumber();
            }
        }
        return number;
    }

    @Override
    public CartCheckoutVo checkout(CartCheckoutParam cartCheckoutParam) {
        //整合shiro
        int userId = getUserId();
        CouponUserExample couponUserExample1 = new CouponUserExample();
        couponUserExample1.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        List<CouponUser> couponUsers1 = couponUserMapper.selectByExample(couponUserExample1);

        Integer addressId = cartCheckoutParam.getAddressId();
        Integer cartId = cartCheckoutParam.getCartId();
        Integer couponId = cartCheckoutParam.getCouponId();

        Integer userCouponId = cartCheckoutParam.getUserCouponId();
        if (userCouponId == -1) {
            userCouponId = couponUsers1.get(0).getId();
        }
        Integer grouponRulesId = cartCheckoutParam.getGrouponRulesId();


        CartExample cartExample = new CartExample();
        if(cartId == 0){
            cartExample.createCriteria().andUserIdEqualTo(userId).andCheckedEqualTo(true).andDeletedEqualTo(false);
        }else{
            cartExample.createCriteria().andIdEqualTo(cartId);
        }


        List<Cart> carts = cartMapper.selectByExample(cartExample);
        int goodsTotalPrice = 0;
        ArrayList<CartCheckedListBean> cartCheckedListBeans = new ArrayList<>();
        for (Cart cart : carts) {
            CartCheckedListBean cartCheckedListBean = new CartCheckedListBean(
                    cart.getId(),
                    cart.getUserId(),
                    cart.getGoodsId(),
                    cart.getGoodsSn(),
                    cart.getGoodsName(),
                    cart.getProductId(),
                    cart.getPrice().intValue(),
                    cart.getNumber(),
                    cart.getSpecifications(),
                    cart.getChecked(),
                    cart.getPicUrl(),
                    cart.getAddTime(),
                    cart.getUpdateTime(),
                    cart.getDeleted());
            cartCheckedListBeans.add(cartCheckedListBean);
            goodsTotalPrice += cart.getNumber() * cart.getPrice().doubleValue();
        }
        CartCheckoutAddressBean cartCheckoutAddressBean = new CartCheckoutAddressBean();

        if(addressId == 0){
            cartCheckoutAddressBean = new CartCheckoutAddressBean();
            cartCheckoutAddressBean.setId(0);
        }else{
            Address address = addressMapper.selectByPrimaryKey(addressId);
            cartCheckoutAddressBean = new CartCheckoutAddressBean(
                    address.getId(),
                    address.getName(),
                    address.getUserId(),
                    address.getProvince(),
                    address.getCity(),
                    address.getCounty(),
                    address.getAddressDetail(),
                    address.getAreaCode(),
                    address.getTel(),
                    address.getIsDefault(),
                    address.getAddTime(),
                    address.getUpdateTime(),
                    address.getDeleted());
        }


        WXShowSelectCouponVO selectCoupon = wxCouponService.getSelectCoupon(userId);
        List<WXSelectInnerCoupon> list = selectCoupon.getList();
        int available = 0;
        int couponPrice = 0;


        if (couponId != -1 && couponId != 0) {
            if (list != null) {
                for (WXSelectInnerCoupon wxSelectInnerCoupon : list) {
                    if (wxSelectInnerCoupon.getAvailable() == true) {
                        available++;
                    }
                }
            }
            Coupon coupon = couponMapper.selectByPrimaryKey(couponId);
            couponPrice = coupon.getDiscount().intValue();
        } else if (couponId == -1) {
            if (list != null) {
                for (WXSelectInnerCoupon wxSelectInnerCoupon : list) {
                    if (wxSelectInnerCoupon.getAvailable() == true) {
                        available++;
                    }
                }
            }
        }else{
        }


        int temp = goodsTotalPrice - couponPrice;
        int fregihtPrice = 0;
        if (temp < 88) {
            fregihtPrice = 8;
        }
        int actualTotalPrice = temp + fregihtPrice;
        int orderTotalPrice = actualTotalPrice;

        CartCheckoutVo cartCheckoutVo = new CartCheckoutVo();
        cartCheckoutVo.setCouponId(couponId);
        cartCheckoutVo.setGrouponRulesId(grouponRulesId);
        cartCheckoutVo.setActualPrice(actualTotalPrice);
        cartCheckoutVo.setOrderTotalPrice(orderTotalPrice);
        cartCheckoutVo.setCartId(cartId);
        cartCheckoutVo.setUserCouponId(userCouponId);
        cartCheckoutVo.setGoodsTotalPrice(goodsTotalPrice);
        cartCheckoutVo.setAddressId(addressId);
        cartCheckoutVo.setGrouponPrice(0.0);
        cartCheckoutVo.setCheckedAddress(cartCheckoutAddressBean);
        cartCheckoutVo.setCouponPrice(couponPrice);
        cartCheckoutVo.setAvailableCouponLength(available);
        cartCheckoutVo.setFreightPrice(fregihtPrice);
        cartCheckoutVo.setCheckedGoodsList(cartCheckedListBeans);
        return cartCheckoutVo;
    }


    //立即购买
    //{"goodsId":1181042,"number":2,"productId":289}
    //响应数据：{"errno":0,"data":50,"errmsg":"成功"}
    @Override
    public int fastadd(Map map) {
        Integer goodsId = (Integer) map.get("goodsId");
        Integer productId = (Integer) map.get("productId");
        int number0 = (int) map.get("number");

        //先拿到该货品的剩余数量
        MarketGoodsProduct marketGoodsProduct3 = marketGoodsProductMapper.selectByPrimaryKey(productId);
        Integer productCurrentNumber = marketGoodsProduct3.getNumber();
        if (number0 > productCurrentNumber) {
            return 0;
        }

        //减去货品的库存
        MarketGoodsProduct marketGoodsProduct1 = marketGoodsProductMapper.selectByPrimaryKey(productId);
        Integer number1 = marketGoodsProduct1.getNumber();
        int productNumber = number1 - number0;
        MarketGoodsProduct marketGoodsProduct2 = new MarketGoodsProduct();
        marketGoodsProduct2.setNumber(productNumber);
        marketGoodsProduct2.setId(productId);
        marketGoodsProductMapper.updateByPrimaryKeySelective(marketGoodsProduct2);


        short number = (short) number0;
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andProductIdEqualTo(productId).andDeletedEqualTo(false);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        Integer id = 0;
        Integer userId = getUserId();
        if (carts.size() == 0) {
            Cart cart = new Cart();
            //整合shiro
            cart.setUserId(userId);
            cart.setGoodsId(goodsId);
            MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(goodsId);
            cart.setGoodsName(marketGoods.getName());
            cart.setGoodsSn(marketGoods.getGoodsSn());
            cart.setProductId(productId);
            MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(productId);
            cart.setPrice(marketGoodsProduct.getPrice());
            cart.setNumber(number);
            cart.setSpecifications(marketGoodsProduct.getSpecifications());
            cart.setChecked(true);
            cart.setPicUrl(marketGoods.getPicUrl());
            Date addTime = new Date();
            cart.setAddTime(addTime);
            cart.setUpdateTime(addTime);
            cart.setDeleted(false);
            cartMapper.insertSelective(cart);
            id = cart.getId();
        }else{
            Cart cart = new Cart();
            cart.setNumber((short) (carts.get(0).getNumber() + number));
            cart.setId(carts.get(0).getId());
            cartMapper.updateByPrimaryKeySelective(cart);
            id = cart.getId();
        }


        CartExample cartExample1 = new CartExample();
        cartExample1.createCriteria().andUserIdEqualTo(userId);
        List<Cart> carts1 = cartMapper.selectByExample(cartExample);
        for (Cart cart : carts1) {
            if (cart.getId() != id) {
                cart.setChecked(false);
                cartMapper.updateByPrimaryKeySelective(cart);
            }
        }
        return id;
    }



    private CartCheckedVo getCartCheckedVo() {
        ArrayList<CartCheckedListBean> cartCheckedListBeans = new ArrayList<>();
        Integer userId = getUserId();
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        int goodsAmount = 0;
        int checkedGoodsAmount = 0;
        int checkedGoodsCount = 0;
        for (Cart cart : carts) {
            if (cart.getChecked() == true) {
                checkedGoodsCount++;
                checkedGoodsAmount += (cart.getPrice().intValue() * cart.getNumber());
            }
            goodsAmount += cart.getPrice().intValue() * cart.getNumber();
            CartCheckedListBean cartListBean = new CartCheckedListBean(
                    cart.getId(),
                    cart.getUserId(),
                    cart.getGoodsId(),
                    cart.getGoodsSn(),
                    cart.getGoodsName(),
                    cart.getProductId(),
                    cart.getPrice().intValue(),
                    cart.getNumber(),
                    cart.getSpecifications(),
                    cart.getChecked(),
                    cart.getPicUrl(),
                    cart.getAddTime(),
                    cart.getUpdateTime(),
                    cart.getDeleted());
            cartCheckedListBeans.add(cartListBean);
        }
        CartCheckedTotalBean cartCheckedTotalBean = new CartCheckedTotalBean();
        cartCheckedTotalBean.setCheckedGoodsCount(checkedGoodsCount);
        cartCheckedTotalBean.setCheckedGoodsAmount(checkedGoodsAmount);
        cartCheckedTotalBean.setGoodsAmount(goodsAmount);
        cartCheckedTotalBean.setGoodsCount(carts.size());
        CartCheckedVo cartCheckedVo = new CartCheckedVo();
        cartCheckedVo.setCartList(cartCheckedListBeans);
        cartCheckedVo.setCartTotal(cartCheckedTotalBean);
        return cartCheckedVo;
    }
}
